package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.apis.article.IArticleClient;
import com.heima.article.feign.ArticleClient;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.dtos.ApArticleDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.wemedia.dtos.ArticleDto;
import com.heima.model.wemedia.dtos.NewsDto;
import com.heima.model.wemedia.pojos.Channel;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.wemedia.mapper.ChannelMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.service.WmNewsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @author 嘉德罗斯
 * @date 2021/11/22
 */
@Service
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper,WmNews> implements WmNewsService {

    @Autowired
    private WmNewsMapper wmNewsMapper;

    @Autowired
    private ChannelMapper channelMapper;

    @Autowired
    private IArticleClient iArticleClient;

    @Autowired
    private FileStorageService fileStorageService;


    @Override
    //查看文章
    public ResponseResult find(NewsDto dto, Integer id) {
        LambdaQueryWrapper <WmNews> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WmNews::getUserId,id);
        if (dto.getKeyword()!=null&&dto.getKeyword().length()>0){
            queryWrapper.like(WmNews::getTitle,dto.getKeyword());
        }
        if (dto.getBeginPubDate()!=null&&dto.getEndPubDate()!=null){
            queryWrapper.ge(WmNews::getPublishTime,dto.getBeginPubDate());
            queryWrapper.le(WmNews::getPublishTime,dto.getBeginPubDate());
        }
        if(dto.getChannelId()!=null){
            queryWrapper.eq(WmNews::getChannelId,dto.getChannelId());
        }
        if (dto.getStatus()!=null){
            queryWrapper.eq(WmNews::getStatus,dto.getStatus());
        }
        queryWrapper.orderByDesc(WmNews::getSubmitedTime);
        IPage<WmNews> page = new Page(dto.getPage(),dto.getSize());
        page = page(page,queryWrapper);
        List<WmNews> records = page.getRecords();
        return ResponseResult.okResult(records);
    }

    @Override
    //下载文章
    public ResponseResult down(Map map) {
        Object i = map.get("id");
        int id = Integer.parseInt(i.toString());
        WmNews wmNews = wmNewsMapper.selectById(id);
        String url = iArticleClient.down(wmNews.getArticleId());
        byte[] bytes = fileStorageService.downLoadFile(url);
        File dir = new File("D:\\file");
        if (!dir.exists()&&dir.isDirectory()){
            dir.mkdirs();
        }
        String uuid = UUID.randomUUID().toString();
        BufferedOutputStream bos = null;
        FileOutputStream fileOutputStream = null;
        try {
            File file = new File("D:\\file\\" + uuid + ".html");
            fileOutputStream = new FileOutputStream(file);
            bos = new BufferedOutputStream(fileOutputStream);
            bos.write(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                bos.close();
                fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        return ResponseResult.okResult(200,"下载成功");
    }

    @Override
    //上传文章
    public WmNews submit(ArticleDto dto, Integer id) {
        WmNews wmNews = new WmNews();
        wmNews.setChannelId(dto.getChannelId());
        wmNews.setCreatedTime(new Date());
        String[] images = dto.getImages();
        String im="";
        for (String image : images) {
            im+=image;
            im+=",";
        }
        im = im.substring(0,im.length()-1);
        wmNews.setImages(im);
        wmNews.setTitle(dto.getTitle());
        wmNews.setContent(dto.getContent());
        wmNews.setUserId(id);
        wmNews.setContent(dto.getContent());
        Short type = Short.valueOf(dto.getType());
        wmNews.setType(type);
        wmNews.setLabels(dto.getLabels());
        wmNews.setSubmitedTime(new Date());
        wmNews.setStatus(dto.getStatus());
        wmNews.setEnable((short) 1);
        wmNews.setPublishTime(dto.getPublishTime());
        ApArticleDto apArticleDto = new ApArticleDto(dto);
        apArticleDto.setAuthorId(id.longValue());
        Channel channel = channelMapper.selectById(dto.getChannelId());
        apArticleDto.setChannelName(channel.getName());
        ResponseResult responseResult = iArticleClient.saveArticle(apArticleDto);
        Object data = responseResult.getErrorMessage();
        Long aid = Long.valueOf(data.toString());
        if (dto.getId() == null){
            wmNews.setArticleId(aid);
            wmNews.setStatus((short) 9);
            wmNews.setReason("审核通过");
            wmNewsMapper.insert(wmNews);
        }else {
            wmNews.setArticleId(aid);
            wmNews.setId(dto.getId());
            wmNews.setStatus((short) 9);
            wmNews.setReason("审核通过");
            wmNews.setArticleId(aid);
            wmNewsMapper.updateById(wmNews);
        }
        return wmNews;
    }

    @Override
    //修改回显数据
    public ResponseResult echo(Integer id) {
        WmNews wmNews = wmNewsMapper.selectById(id);
        return ResponseResult.okResult(wmNews);
    }

    @Override
    //删除文章
    public void delete(Integer id) {
        WmNews wmNews = wmNewsMapper.selectById(id);
        if (wmNews.getArticleId()!=null){
            iArticleClient.delete(wmNews.getArticleId());
        }
        wmNewsMapper.deleteById(id);
    }

}
